<template>
  <div>
    <div
      class="box-card"
      id="card_pdf"
      ref="pdfContent"
    >
      <p>
        注：行内编辑，双击单元格调出单元格编辑，修改数据，鼠标离开单元格完成修改
        <el-button
          type="primary"
          @click="exportPDF"
        >导出页面</el-button>
      </p>
      <el-table
        ref="table"
        :data="tableList"
        border
        style="width: 100%"
        :height="tableHeight"
        @cell-dblclick="tableDbEdit"
      >
        <el-table-column
          prop="title"
          label="标题"
        >
          <template slot-scope="scope">
            <!-- 条件判断如果满足则显示表单，否则默认展示文字 -->
            <el-input
              size="small"
              v-model="scope.row.title"
              v-if="showInput == `title${scope.row.id}`"
              @blur="blurInput(scope.row.id, 'title', scope.row.title)"
              v-focus
            >
            </el-input>
            <p v-else>{{ scope.row.title }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
        >
          <template slot-scope="scope">
            <el-input
              size="small"
              v-model="scope.row.name"
              v-if="showInput === `name${scope.row.id}`"
              @blur="blurInput(scope.row.id, 'name', scope.row.name)"
              v-focus
            >
            </el-input>
            <p v-else>{{ scope.row.name }}</p>
          </template>
        </el-table-column>
        <el-table-column
          label="品种"
          prop="type"
        >
          <template slot-scope="scope">
            <el-input
              size="small"
              v-model="scope.row.type"
              v-if="showInput === `type${scope.row.id}`"
              @blur="blurInput(scope.row.id, 'type', scope.row.type)"
              v-focus
            >
            </el-input>
            <p v-else>{{ scope.row.type }}</p>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              @click="delClick(scope.row)"
              icon="el-icon-delete"
              type="danger"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 460px;display: flex;margin-top: 16px;">
        <xCard
          :title="'折线图数据'"
          width="800px"
          style="margin-right: 16px;"
        >
          <div
            id="chart"
            style="height: 100%;"
          >
          </div>
        </xCard>
        <xCard
          :title="'饼图数据'"
          width="400px"
        >
          <div
            id="chart2"
            style="height: 100%;"
          >
          </div>
        </xCard>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import xCard from '../Card/cards/card.vue'
import bgCard from '../Card/cards/bgCard.vue'
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
  components: {
    xCard,
    bgCard
  },
  data () {
    return {
      tableList: [
        {
          // 表格数据
          id: 0,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 1,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 2,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 3,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 4,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 5,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 6,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 7,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
        {
          id: 8,
          name: "王皮皮",
          title: "在家小霸王，出门小王八",
          type: "中华田园猫",
        },
      ],
      showInput: "",
      oldData: {},
      tableHeight: 300,
      originalHeight: null // 存储原始高度
    };
  },
  directives: {
    // 通过自定义指令实现的表单自动获得光标的操作
    focus: {
      inserted: function (el) {
        if (el.tagName.toLocaleLowerCase() === "input") {
          el.focus();
        } else {
          if (el.getElementsByTagName("input")) {
            el.getElementsByTagName("input")[0].focus();
          }
        }
        el.focus();
      },
    },
  },
  mounted () {
    this.getEcharts()
    this.getEcharts2()
  },
  // 方法
  methods: {
    getEcharts () {
      var chartDom = document.getElementById('chart')
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#FEDAB7',
              type: 'solid',
              width: 2
            }
          },
          showContent: true,
        },
        color: ['#B2C9E4', '#2C3838'],
        legend: {
          top: 20,
          right: 10,
          data: ['数据一', '数据二'],
          textStyle: {
            color: '#ccc',
          }
        },
        grid: {
          top: '20%',
          left: '3%',
          right: '4%',
          bottom: '6%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['壹月', '贰月', '叁月', '肆月', '伍月', '陸月', '柒月', '捌月', '玖月', '拾月', '拾壹月', '拾贰月'],
          axisLine: {
            show: true,
            symbolSize: [6, 10],
            lineStyle: {
              color: '#ccc',
            }
          },
          axisTick: {
            show: false,
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false,
            lineStyle: {
              color: '#ccc',
            }
          }
        },
        series: [
          {
            name: '数据一',
            type: 'line',
            symbol: 'emptyCircle',
            legendHoverLink: true,
            symbolSize: 8,
            stack: 'Total',
            lineStyle: {
              shadowColor: 'rgba(0, 0, 0, 0.2)',
              shadowBlur: 5,
              shadowOffsetX: 2,
              shadowOffsetY: 3,
              opacity: 1,
            },
            data: [120, 132, 101, 134, 90, 230, 210, 134, 90, 230, 21, 62]
          },
          {
            name: '数据二',
            type: 'line',
            symbol: 'emptyCircle',
            legendHoverLink: true,
            symbolSize: 8,
            stack: 'Total',
            lineStyle: {
              shadowColor: 'rgba(0, 0, 0, 0.2)',
              shadowBlur: 5,
              shadowOffsetX: 2,
              shadowOffsetY: 3,
              opacity: 1,
            },
            data: [220, 182, 191, 234, 290, 330, 310, 90, 230, 210, 134, 90]
          }
        ]
      }
      option && myChart.setOption(option)
    },
    getEcharts2 () {
      var chartDom = document.getElementById('chart2')
      const myChart = echarts.init(chartDom)
      const option = {
        title: {
          text: 'Referer of a Website',
          subtext: 'Fake Data',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          show: false,
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 1048, name: 'Search Engine' },
              { value: 735, name: 'Direct' },
              { value: 580, name: 'Email' },
              { value: 484, name: 'Union Ads' },
              { value: 300, name: 'Video Ads' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      option && myChart.setOption(option)
    },
    // 当input失去光标后进行的操作
    async blurInput (id, name, value) {
      const obj = {};
      // 判断数据是否有所改变，如果数据有改变则调用修改接口
      if (this.oldData[name] !== value) {
        obj[name] = value; // 被改变的数据
        // 然后再写调用接口，提交内容的东西就可以了
      }
      this.showInput = "";
    },
    /* 方法参数皆为框架方法的默认传参 row 行数据 column被点击的触发了方法的单元格event事件 */
    tableDbEdit (row, column, event) {
      this.showInput = column.property + row.id;
      this.oldData[column.property] = row[column.property];
    },
    delClick (row) {
      console.log('row', row)
    },
    async exportPDF () {
      this.tableHeight = 'auto'; // 临时取消高度限制
      try {
        // 等待DOM更新
        await this.$nextTick();
        // 2. 获取完整内容
        const element = this.$refs.pdfContent;
        // 3. 使用html2canvas捕获完整内容
        const canvas = await html2canvas(element, {
          scale: 2,
          logging: false,
          useCORS: true,
          backgroundColor: '#FFFFFF',
          scrollY: 0, // 确保从顶部开始捕获
          windowHeight: element.scrollHeight // 设置窗口高度为元素完整高度
        });
        // 5. 生成PDF
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgWidth = 210;
        const pageHeight = 295;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let heightLeft = imgHeight;
        let position = 0;

        pdf.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          pdf.addPage();
          pdf.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight);
          heightLeft -= pageHeight;
        }
        pdf.save('完整表格导出.pdf');
        this.tableHeight = 300

      } catch (error) {
        console.error('导出失败:', error);
        // 确保出错时也恢复表格高度
        if (this.$refs.table && this.originalHeight !== null) {
          this.$refs.table.height = this.originalHeight;
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-card {
  height: calc(100vh - 80px);
}
#app {
  width: 1000px;
  margin: 0 auto;
}
</style>
